﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    /// <summary>
    /// 删除溯源基本信息
    /// </summary>
    public class DelTraceabilityHandler : IRequestHandler<DelTraceabilityCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<TraceabilityModel> traceabilityRepo;
        private readonly IMapper mapper;

        public DelTraceabilityHandler(IBaseRepository<TraceabilityModel> traceabilityRepo,IMapper mapper) 
        {
            this.traceabilityRepo = traceabilityRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelTraceabilityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var traceability = traceabilityRepo.GetAll().Where(x => x.Id == request.Id).FirstOrDefault();
            traceability = mapper.Map(request, traceability);
            traceability.IsDelete = true;
            var i = traceabilityRepo.Update(traceability);
            if (i>0)
            {
                res.Code = ApiEnum.Success;
                res.Data = i;
                res.Msg = "删除成功";
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Data = i;
                res.Msg = "删除失败";
            }
            return Task.FromResult(res);
        }
    }
}
